package com.woniu.carrent.controller;

import com.woniu.carrent.util.BookingTools;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.LocalDate;
import java.util.Map;


@RestController
@CrossOrigin
//@SaCheckLogin
public class OpenAiController {
    private final ChatClient chatClient;
    private final BookingTools bookingTools;
    /**
     * AI助手
     */
    public OpenAiController(ChatClient.Builder chatClientBuilder,
                            ChatMemory chatMemory,
                            BookingTools bookingTools) {
        this.bookingTools = bookingTools;
        this.chatClient = chatClientBuilder.defaultSystem("""
                          ##角色
                          您是“爱坤”汽车租赁公司的客户聊天支持代理。请以友好、乐于助人且愉快的方式来回复。
                          您正在通过在线聊天系统与客户互动。
                          ##要求
                          1.在提供有关预订车辆或取消预订的信息之前，您必须始终从用户处获取以下信息：预订号、客户姓名。
                          2.在涉及增删改（除了查询）function-call前，必须等用户回复“确认”后再调用tool。
                          3.请讲中文。
                          4.对答的时候可以适当多用表情，更有亲和力

                          今天的日期是 {current_date}.
                     """)//ai角色训练
                .defaultAdvisors(PromptChatMemoryAdvisor.builder(chatMemory).build(),
                        new SimpleLoggerAdvisor())//聊天记忆功能,new一个问答日志
                .defaultTools(bookingTools)//ai管家所用的工具类
                .build();
    }
    @Autowired
    private VectorStore vectorStore;

    @CrossOrigin
    @PostMapping(value = "/ai/generateStreamAsString", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> generateStreamAsString(@RequestBody Map<String, String> payload) {
        String message = payload.get("message");

        Flux<String> content = chatClient.prompt()
                .system(s -> s.param("current_date", LocalDate.now().toString()))
                .user(message + "/no_think")
                .advisors(QuestionAnswerAdvisor.builder(vectorStore)
                        .searchRequest(SearchRequest.builder().similarityThreshold(0.8d).topK(6).build())
                        .build())
                .stream()
                .content();

        return content.concatWith(Flux.just("[complete]"));
    }


}
